package com.gitee.freakchicken.dbapi.basic.controller;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dbapi.apple.SqlMeta;
import com.dbapi.apple.verify.SpecManager;
import com.gitee.freakchicken.dbapi.basic.domain.DataSource;
import com.gitee.freakchicken.dbapi.basic.domain.Group;
import com.gitee.freakchicken.dbapi.basic.service.C_zBe6wc23;
import com.gitee.freakchicken.dbapi.basic.service.C_qHUtLNkz;
import com.gitee.freakchicken.dbapi.basic.service.C_t1Kvj7mO;
import com.gitee.freakchicken.dbapi.basic.util.Constants;
import com.gitee.freakchicken.dbapi.basic.util.C_LS6YRMwy;
import com.gitee.freakchicken.dbapi.basic.util.C_66X3zUSZ;
import com.gitee.freakchicken.dbapi.basic.util.C_1aiKTlVp;
import com.gitee.freakchicken.dbapi.basic.util.C_3CjyYmwF;
import com.gitee.freakchicken.dbapi.basic.util.C_J29NqcbG;
import com.gitee.freakchicken.dbapi.common.ApiConfig;
import com.gitee.freakchicken.dbapi.common.ApiPluginConfig;
import com.gitee.freakchicken.dbapi.common.ResponseDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/apiConfig")
public class C_qrmyow6r {

    @Value("${dbapi.mode}")
    String gf_nTGtQuAM;

    @Autowired
    C_zBe6wc23 gf_zudWefbN;

    @Autowired
    C_qHUtLNkz gf_I6xo5qAP;

    @Autowired
    C_t1Kvj7mO gf_dQctuHLa;

    @Value("${dbapi.api.context}")
    String gf_iEuStJyI;

    @RequestMapping("/context")
    public String m_o9Li7urR() {
        return gf_iEuStJyI;
    }

    @RequestMapping("/add")
    public ResponseDto m_XzwWOoOV(@RequestBody JSONObject jo) {
        ApiConfig lf_T6Ge83ST = new ApiConfig();
        lf_T6Ge83ST.setName(jo.getString("name"));
        lf_T6Ge83ST.setPath(jo.getString("path"));
        lf_T6Ge83ST.setNote(jo.getString("note"));
        lf_T6Ge83ST.setGroupId(jo.getString("groupId"));
        lf_T6Ge83ST.setContentType(jo.getString("contentType"));
        lf_T6Ge83ST.setJsonParam(jo.getString("jsonParam"));
        lf_T6Ge83ST.setParams(jo.getJSONArray("paramsJson").toString(SerializerFeature.WriteMapNullValue));
        lf_T6Ge83ST.setAccess(jo.getInteger("access"));
        lf_T6Ge83ST.setTask(jo.getJSONArray("taskJson").toString(SerializerFeature.WriteMapNullValue));
        lf_T6Ge83ST.setStatus(Constants.API_STATUS_OFFLINE);
        String lf_phSNVwRf = C_J29NqcbG.m_fjXhGnD5();
        lf_T6Ge83ST.setId(lf_phSNVwRf);
        lf_T6Ge83ST.setCreateUserId(C_3CjyYmwF.m_j3EEUXak());
        JSONArray lf_jbJsXmUQ = jo.getJSONArray("alarmPlugins");
        lf_jbJsXmUQ.add(jo.getJSONObject("cachePlugin"));
        lf_jbJsXmUQ.add(jo.getJSONObject("globalTransformPlugin"));
        List<ApiPluginConfig> lf_3X65INal = lf_jbJsXmUQ.toJavaList(ApiPluginConfig.class);
        List<ApiPluginConfig> lf_x4zk9I8G = lf_3X65INal.stream().filter(lambda_lf_vwoh64oF -> lambda_lf_vwoh64oF != null && StringUtils.isNotEmpty(lambda_lf_vwoh64oF.getPluginName())).collect(Collectors.toList());
        lf_x4zk9I8G.forEach(lambda_lf_N8qMYsw1 -> lambda_lf_N8qMYsw1.setApiId(lf_phSNVwRf));
        return gf_zudWefbN.m_IBOVpFT1(lf_T6Ge83ST, lf_x4zk9I8G);
    }

    @Deprecated
    @RequestMapping("/parseParam")
    public ResponseDto m_z8Ky4uRb(String sql) {
        try {
            Set<String> lf_iuQA1Lnk = C_1aiKTlVp.m_eX8mI2M8().parseParameter(sql);
            List<JSONObject> lf_FbXQxX5g = lf_iuQA1Lnk.stream().map(lambda_lf_RA9nA9ns -> {
                JSONObject lf_d1V4iVLY = new JSONObject();
                lf_d1V4iVLY.put("value", lambda_lf_RA9nA9ns);
                return lf_d1V4iVLY;
            }).collect(Collectors.toList());
            return ResponseDto.successWithData(lf_FbXQxX5g);
        } catch (Exception e) {
            return ResponseDto.fail(e.getMessage());
        }
    }

    @RequestMapping("/getAll")
    public List<ApiConfig> m_K8SQmQd7() {
        return gf_zudWefbN.m_TWyG7uSd();
    }

    @RequestMapping("/getApiTree")
    public List<JSONObject> m_zCEHL9rH() {
        return gf_zudWefbN.m_LdUUauNb();
    }

    @RequestMapping("/search")
    public List<ApiConfig> m_Jwi0FTtv(String name, String note, String path, String groupId) {
        return gf_zudWefbN.m_E1R6kkVh(name, note, path, groupId);
    }

    @RequestMapping("/detail/{id}")
    public ApiConfig m_eXdDuJ3W(@PathVariable String id) {
        return gf_zudWefbN.m_NiQeShsu(id);
    }

    @RequestMapping("/delete/{id}")
    public void m_hapPDGL8(@PathVariable String id) {
        gf_zudWefbN.m_KNv8mGE3(id);
    }

    @RequestMapping("/update")
    public ResponseDto m_Z676q46t(@RequestBody JSONObject jo) {
        ApiConfig lf_sR2DwXBW = new ApiConfig();
        lf_sR2DwXBW.setId(jo.getString("id"));
        lf_sR2DwXBW.setName(jo.getString("name"));
        lf_sR2DwXBW.setPath(jo.getString("path"));
        lf_sR2DwXBW.setNote(jo.getString("note"));
        lf_sR2DwXBW.setGroupId(jo.getString("groupId"));
        lf_sR2DwXBW.setContentType(jo.getString("contentType"));
        lf_sR2DwXBW.setJsonParam(jo.getString("jsonParam"));
        lf_sR2DwXBW.setParams(jo.getJSONArray("paramsJson").toString(SerializerFeature.WriteMapNullValue));
        lf_sR2DwXBW.setAccess(jo.getInteger("access"));
        lf_sR2DwXBW.setTask(jo.getJSONArray("taskJson").toString(SerializerFeature.WriteMapNullValue));
        lf_sR2DwXBW.setStatus(Constants.API_STATUS_OFFLINE);
        JSONArray lf_MbNuTYJx = jo.getJSONArray("alarmPlugins");
        lf_MbNuTYJx.add(jo.getJSONObject("cachePlugin"));
        lf_MbNuTYJx.add(jo.getJSONObject("globalTransformPlugin"));
        List<ApiPluginConfig> lf_qOwN07dW = lf_MbNuTYJx.toJavaList(ApiPluginConfig.class);
        List<ApiPluginConfig> lf_n4JdzPTx = lf_qOwN07dW.stream().filter(lambda_lf_7TyD9kr9 -> lambda_lf_7TyD9kr9 != null && StringUtils.isNotEmpty(lambda_lf_7TyD9kr9.getPluginName())).collect(Collectors.toList());
        return gf_zudWefbN.m_J7reVmRz(lf_sR2DwXBW, lf_n4JdzPTx);
    }

    @RequestMapping("/online/{id}")
    public void m_ANYDSaRo(@PathVariable String id) {
        gf_zudWefbN.m_4ncBDIaY(id);
    }

    @RequestMapping("/offline/{id}")
    public void m_O4dNHtoN(@PathVariable String id) {
        gf_zudWefbN.m_RIvma2dh(id);
    }

    @RequestMapping("/apiDocs")
    public void m_3td1xYXq(String ids, HttpServletResponse response) {
        List<String> lf_jXONS45Y = Arrays.asList(ids.split(","));
        String lf_mxPCZH77 = gf_zudWefbN.m_mQx5WE6w(lf_jXONS45Y);
        response.setContentType("application/x-msdownload;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=API docs.md");
        OutputStream lf_Pd5y0PTW = null;
        try {
            lf_Pd5y0PTW = response.getOutputStream();
            lf_Pd5y0PTW.write(lf_mxPCZH77.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (lf_Pd5y0PTW != null)
                    lf_Pd5y0PTW.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/downloadConfig")
    public void m_4HzVrnt2(String ids, HttpServletResponse response) {
        List<String> lf_tjRQYOR9 = Arrays.asList(ids.split(","));
        JSONObject lf_7k5JDBFR = gf_zudWefbN.m_or1nlDhd(lf_tjRQYOR9);
        String lf_wzSRZzkK = lf_7k5JDBFR.toString(SerializerFeature.WriteMapNullValue);
        response.setContentType("application/x-msdownload;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=api_config.json");
        OutputStream lf_7fJlvux8 = null;
        try {
            lf_7fJlvux8 = response.getOutputStream();
            lf_7fJlvux8.write(lf_wzSRZzkK.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (lf_7fJlvux8 != null)
                    lf_7fJlvux8.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/downloadGroupConfig")
    public void m_qQJGhShS(String ids, HttpServletResponse response) {
        List<String> lf_CWb8YEkB = Arrays.asList(ids.split(","));
        List<Group> lf_mZGENjIG = gf_dQctuHLa.m_fJQhm0Q7(lf_CWb8YEkB);
        String lf_AUrQqQrE = JSON.toJSONString(lf_mZGENjIG);
        response.setContentType("application/x-msdownload;charset=utf-8");
        OutputStream lf_k0FHdbs9 = null;
        try {
            lf_k0FHdbs9 = response.getOutputStream();
            lf_k0FHdbs9.write(lf_AUrQqQrE.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (lf_k0FHdbs9 != null)
                    lf_k0FHdbs9.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/import", produces = "application/json;charset=UTF-8")
    public void m_wXRZEe2p(@RequestParam("file") MultipartFile file) throws IOException {
        String lf_chRHpi7z = IOUtils.toString(file.getInputStream(), "utf-8");
        JSONObject lf_kGtQsLa0 = JSON.parseObject(lf_chRHpi7z);
        List<ApiConfig> lf_dcYt9Hyb = lf_kGtQsLa0.getJSONArray("api").toJavaList(ApiConfig.class);
        Integer lf_SiPaAHzD = gf_zudWefbN.m_TNn3p60b();
        if ((lf_SiPaAHzD + lf_dcYt9Hyb.size()) > SpecManager.getApiNum()) {
            throw new RuntimeException("The number of API exceeds the limit");
        }
        lf_dcYt9Hyb.stream().forEach(lambda_lf_PB9ip1xf -> {
            lambda_lf_PB9ip1xf.setCreateUserId(C_3CjyYmwF.m_j3EEUXak());
            lambda_lf_PB9ip1xf.setCreateTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss"));
            lambda_lf_PB9ip1xf.setUpdateTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss"));
        });
        List<ApiPluginConfig> lf_qGiGYNkq = lf_kGtQsLa0.getJSONArray("plugins").toJavaList(ApiPluginConfig.class);
        gf_zudWefbN.m_dfkU5V82(lf_dcYt9Hyb, lf_qGiGYNkq);
    }

    @RequestMapping(value = "/importGroup", produces = "application/json;charset=UTF-8")
    public void m_GcWX9KMT(@RequestParam("file") MultipartFile file) throws IOException {
        String lf_LxonYDL9 = IOUtils.toString(file.getInputStream(), "utf-8");
        List<Group> lf_nZborW9u = JSON.parseArray(lf_LxonYDL9, Group.class);
        Integer lf_9iuzhDqC = gf_dQctuHLa.m_g0gslmyQ();
        if ((lf_9iuzhDqC + lf_nZborW9u.size()) > SpecManager.getGroupNum()) {
            throw new RuntimeException("The number of groups exceeds the limit");
        }
        lf_nZborW9u.stream().forEach(lambda_lf_3zfOCTog -> {
            lambda_lf_3zfOCTog.setCreateUserId(C_3CjyYmwF.m_j3EEUXak());
            lambda_lf_3zfOCTog.setCreateTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss"));
            lambda_lf_3zfOCTog.setUpdateTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss"));
        });
        gf_dQctuHLa.m_IKYmJsjA(lf_nZborW9u);
    }

    @RequestMapping("/sql/execute")
    public ResponseDto m_hKM35Pcw(String datasourceId, String sql, String params) {
        DruidPooledConnection lf_cLBJe6ov = null;
        try {
            DataSource lf_9yLbgAes = gf_I6xo5qAP.m_NQrcJ8gx(datasourceId);
            lf_cLBJe6ov = C_66X3zUSZ.m_SWdS8zKL(lf_9yLbgAes);
            Map<String, Object> lf_uCalG6Ua = JSON.parseObject(params, Map.class);
            SqlMeta lf_S63a4ced = C_1aiKTlVp.m_eX8mI2M8().parse(sql, lf_uCalG6Ua);
            Object lf_E19MlLhH = C_LS6YRMwy.m_z0KssRWe(lf_cLBJe6ov, lf_S63a4ced.getSql(), lf_S63a4ced.getJdbcParamValues());
            return ResponseDto.successWithData(lf_E19MlLhH);
        } catch (Exception e) {
            return ResponseDto.fail(e.getMessage());
        } finally {
            try {
                if (lf_cLBJe6ov != null)
                    lf_cLBJe6ov.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/parseDynamicSql")
    public ResponseDto m_4N02xt3m(String sql, String params) {
        try {
            Map<String, Object> lf_2oDTCnK0 = JSON.parseObject(params, Map.class);
            SqlMeta lf_V8WH0bGH = C_1aiKTlVp.m_eX8mI2M8().parse(sql, lf_2oDTCnK0);
            return ResponseDto.successWithData(lf_V8WH0bGH);
        } catch (Exception e) {
            return ResponseDto.fail(e.getMessage());
        }
    }
}
